package com.atguigu.read_write_lock.lock_down;

import com.atguigu.read_write_lock.ReadWriteLockDemo1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RWLockDoownDemo1 {
    private int num = 0;
    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private Lock readLock = readWriteLock.readLock();
    private Lock writeLock = readWriteLock.writeLock();

    public static void main(String[] args) {
        RWLockDoownDemo1 rwDemo1 = new RWLockDoownDemo1();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
//                System.out.print(Thread.currentThread().getName());
                rwDemo1.write();
            }, String.valueOf(i)).start();
        }
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
//                System.out.print(Thread.currentThread().getName());
                rwDemo1.read();
            }, String.valueOf(i)).start();
        }

    }


    public void write() {
        writeLock.lock();
        try {
            System.out.println("在写入之前: num = " + num);
            ++num;
            readLock.lock();    //先抢锁
        }finally {
            writeLock.unlock();
        }

        try{
            read();
        }finally {
            readLock.unlock();
        }
    }

    public void read() {
        Lock lock = readLock;
        lock.lock();
        try {
            System.out.println(this.num);
        }finally {
            lock.unlock();
        }
    }
}